package com.hzw.saas.web.admin.job.task;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.hzw.saas.api.hpc.IHpcAccountRecordService;
import com.hzw.saas.api.hpc.bo.HpcAccountAmountDailyBo;
import com.hzw.saas.api.hpc.bo.HpcAccountRecordBo;
import com.hzw.saas.common.quartz.model.ScheduleJob;
import com.hzw.saas.common.util.Json;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *   补充HPC
 * </p>
 *
 * @author sonam
 * @since 2021/6/1 19:32
 */
@Slf4j
@Service("recordHpcAccountBalanceTask")
public class RecordBalanceTask {

    @Resource(name = "hpcAccountRecordServiceImpl")
    private IHpcAccountRecordService hpcAccountRecordService;

    public void recordHpcBalance(ScheduleJob scheduleJob) {
        Date startTime = parseParams(scheduleJob.getParams());

        List<HpcAccountRecordBo> list = hpcAccountRecordService.getList();
        list.forEach(data -> {
            Date createTime = data.getCreateTime();
            Date endTime = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -2));
            createTime = DateUtil.compare(createTime, startTime) > 0 ? createTime : startTime;

            if(DateUtil.compare(createTime, endTime) > 0) {
                // skip～
                return;
            }

            long between = DateUtil.between(createTime, endTime, DateUnit.DAY);
            for(int i = 0 ; i <= between; i ++) {
                try {
                    HpcAccountAmountDailyBo hpcAccountAmountDailyBo = hpcAccountRecordService.recordHpcBalanceByDate(data.getPid(), createTime);
                    log.info("记录HPC帐号{},在{}余额为:{}", data.getHpcAccountSnapshot(), hpcAccountAmountDailyBo.getBusTime(), hpcAccountAmountDailyBo.getCurCoreTimeBalance());
                } catch (Exception e) {
                    log.error("记录HPC账户余额失败", e);
                }
                createTime = DateUtil.offsetDay(createTime, 1);
            }
        });

    }

    private Date parseParams(String params) {
        Date startTime;
        try {
            Map<String, String> map = Json.getObjectMapper().readValue(params, Map.class);
            startTime = DateUtil.parse(map.get("startTime"));
        } catch (Exception e) {
            e.printStackTrace();
            startTime = new Date();
        }
        return startTime;
    }

}
